<template>
	<view class="profile-container">
		<view class="profile-header">
			<view class="user-info">
				<view class="avatar-container" @click="changeAvatar" v-if="userInfo.isLogin">
					<image :src="userInfo.avatar" class="avatar" mode="aspectFill"></image>
					<view class="avatar-overlay">
						<uni-icons type="camera" size="20" color="#ffffff"></uni-icons>
						<text class="avatar-text">更换头像</text>
					</view>
				</view>
				<image v-else :src="userInfo.avatar" class="avatar" mode="aspectFill"></image>
				<view class="user-details">
					<text class="username">{{ userInfo.username }}</text>
					<text class="user-level">{{ userInfo.level }}</text>
				</view>
				<view class="login-btn" v-if="!userInfo.isLogin" @click="goToLogin">
					<text>登录</text>
				</view>
			</view>
			
			<view class="stats-section">
				<view class="stat-item">
					<text class="stat-number">{{ userStats.favorites }}</text>
					<text class="stat-label">收藏</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ userStats.history }}</text>
					<text class="stat-label">观看</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ userStats.reviews }}</text>
					<text class="stat-label">评价</text>
				</view>
			</view>
		</view>
		
		<view class="menu-sections">
			<view class="menu-section">
				<view class="section-title">我的内容</view>
				<view class="menu-list">
					<view class="menu-item" @click="goToFavorites">
						<uni-icons type="heart" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">我的收藏</text>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
					<view class="menu-item" @click="goToHistory">
						<uni-icons type="clock" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">观看历史</text>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
					<view class="menu-item" @click="goToReviews">
						<uni-icons type="chat" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">我的评价</text>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 管理员专用菜单 -->
			<view class="menu-section" v-if="userInfo.role === 'admin'">
				<view class="section-title">管理员功能</view>
				<view class="menu-list">
					<view class="menu-item admin-item" @click="goToAdmin">
						<uni-icons type="gear-filled" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text admin-text">管理员后台</text>
						<view class="admin-badge">
							<text class="badge-text">ADMIN</text>
						</view>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
				</view>
			</view>

			<view class="menu-section">
				<view class="section-title">设置</view>
				<view class="menu-list">
					<view class="menu-item" @click="goToSettings">
						<uni-icons type="gear" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">应用设置</text>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
					<view class="menu-item" @click="clearCache">
						<uni-icons type="trash" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">清除缓存</text>
						<text class="cache-size">{{ cacheSize }}</text>
					</view>
					<view class="menu-item" @click="goToAbout">
						<uni-icons type="info" size="20" color="#ff6b35"></uni-icons>
						<text class="menu-text">关于我们</text>
						<uni-icons type="right" size="16" color="#666666"></uni-icons>
					</view>
				</view>
			</view>
			
			<view class="menu-section" v-if="userInfo.isLogin">
				<view class="menu-list">
					<view class="menu-item logout" @click="handleLogout">
						<uni-icons type="loop" size="20" color="#ff4444"></uni-icons>
						<text class="menu-text logout-text">退出登录</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 自定义底部导航栏 -->
		<custom-tabbar :current="2"></custom-tabbar>
	</view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import { useUserStore } from '@/stores/user.js'

export default {
	components: {
		CustomTabbar
	},
	setup() {
		const userStore = useUserStore()
		return {
			userStore
		}
	},
	data() {
		return {
			userInfo: {
				username: '游客用户',
				level: '普通用户',
				avatar: '/static/logo.png',
				isLogin: false
			},
			userStats: {
				favorites: 0,
				history: 0,
				reviews: 0
			},
			cacheSize: '12.5MB'
		}
	},
	onLoad() {
		this.checkLoginStatus()
	},
	onShow() {
		this.checkLoginStatus()
		this.loadUserInfo()
		this.loadUserStats()
	},
	methods: {
		checkLoginStatus() {
			const userInfo = uni.getStorageSync('userInfo')

			// 如果没有登录信息，跳转到登录页
			if (!userInfo || (!userInfo.isLogin && !userInfo.isGuest)) {
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return false
			}
			return true
		},

		loadUserInfo() {
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.userInfo = {
					...this.userInfo,
					...userInfo
				}
			}
		},
		
		loadUserStats() {
			// 加载用户统计数据
			const favorites = uni.getStorageSync('favorites') || []
			const history = uni.getStorageSync('watchHistory') || []
			const reviews = uni.getStorageSync('userReviews') || []
			
			this.userStats = {
				favorites: favorites.length,
				history: history.length,
				reviews: reviews.length
			}
		},
		
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},

		goToAdmin() {
			if (this.userInfo.role !== 'admin') {
				uni.showToast({
					title: '权限不足',
					icon: 'none'
				})
				return
			}
			uni.navigateTo({
				url: '/pages/admin/admin'
			})
		},

		// 修改头像
		changeAvatar() {
			if (!this.userInfo.isLogin) {
				this.showLoginTip()
				return
			}

			uni.showActionSheet({
				itemList: ['从相册选择', '拍照'],
				success: (res) => {
					if (res.tapIndex === 0) {
						this.chooseImageFromAlbum()
					} else if (res.tapIndex === 1) {
						this.chooseImageFromCamera()
					}
				}
			})
		},

		// 从相册选择图片
		chooseImageFromAlbum() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album'],
				success: (res) => {
					this.processSelectedImage(res.tempFilePaths[0])
				},
				fail: () => {
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		},

		// 拍照选择图片
		chooseImageFromCamera() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['camera'],
				success: (res) => {
					this.processSelectedImage(res.tempFilePaths[0])
				},
				fail: () => {
					uni.showToast({
						title: '拍照失败',
						icon: 'none'
					})
				}
			})
		},

		// 处理选择的图片
		processSelectedImage(imagePath) {
			uni.showLoading({
				title: '处理中...'
			})

			// 根据平台选择不同的处理方式
			// #ifdef H5
			this.convertImageToBase64H5(imagePath)
			// #endif

			// #ifndef H5
			// 小程序和App平台使用文件系统管理器
			if (uni.getFileSystemManager) {
				uni.getFileSystemManager().readFile({
					filePath: imagePath,
					encoding: 'base64',
					success: (res) => {
						const base64Data = 'data:image/jpeg;base64,' + res.data
						this.updateUserAvatar(base64Data)
					},
					fail: () => {
						uni.hideLoading()
						uni.showToast({
							title: '图片处理失败',
							icon: 'none'
						})
					}
				})
			} else {
				// 如果不支持文件系统管理器，直接使用图片路径
				this.updateUserAvatar(imagePath)
			}
			// #endif
		},

		// H5平台图片转base64
		// #ifdef H5
		convertImageToBase64H5(imagePath) {
			const canvas = document.createElement('canvas')
			const ctx = canvas.getContext('2d')
			const img = new Image()

			img.onload = () => {
				// 设置canvas尺寸
				canvas.width = img.width
				canvas.height = img.height

				// 绘制图片到canvas
				ctx.drawImage(img, 0, 0)

				// 转换为base64
				try {
					const base64Data = canvas.toDataURL('image/jpeg', 0.8)
					this.updateUserAvatar(base64Data)
				} catch (error) {
					console.error('图片转换失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '图片处理失败',
						icon: 'none'
					})
				}
			}

			img.onerror = () => {
				uni.hideLoading()
				uni.showToast({
					title: '图片加载失败',
					icon: 'none'
				})
			}

			// 设置跨域属性（如果需要）
			img.crossOrigin = 'anonymous'
			img.src = imagePath
		},
		// #endif

		// 更新用户头像
		updateUserAvatar(base64Avatar) {
			try {
				// 更新当前用户信息
				this.userInfo.avatar = base64Avatar

				// 更新存储中的用户信息
				const currentUserInfo = uni.getStorageSync('userInfo')
				if (currentUserInfo) {
					currentUserInfo.avatar = base64Avatar
					uni.setStorageSync('userInfo', currentUserInfo)
				}

				// 更新userStore中的用户数据
				this.userStore.initUserData()
				const userIndex = this.userStore.users.findIndex(u => u.id === currentUserInfo.id)
				if (userIndex !== -1) {
					this.userStore.users[userIndex].avatar = base64Avatar
					this.userStore.saveUsersToStorage()
				}

				uni.hideLoading()
				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				})
			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: '头像更新失败',
					icon: 'none'
				})
			}
		},
		
		goToFavorites() {
			if (!this.userInfo.isLogin) {
				this.showLoginTip()
				return
			}
			uni.showToast({
				title: '收藏页面开发中',
				icon: 'none'
			})
		},
		
		goToHistory() {
			if (!this.userInfo.isLogin) {
				this.showLoginTip()
				return
			}
			uni.showToast({
				title: '历史页面开发中',
				icon: 'none'
			})
		},
		
		goToReviews() {
			if (!this.userInfo.isLogin) {
				this.showLoginTip()
				return
			}
			uni.showToast({
				title: '评价页面开发中',
				icon: 'none'
			})
		},
		
		goToSettings() {
			uni.showToast({
				title: '设置页面开发中',
				icon: 'none'
			})
		},
		
		clearCache() {
			uni.showModal({
				title: '清除缓存',
				content: '确定要清除应用缓存吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除缓存逻辑
						uni.showToast({
							title: '缓存清除成功',
							icon: 'success'
						})
						this.cacheSize = '0MB'
					}
				}
			})
		},
		
		goToAbout() {
			uni.showToast({
				title: '关于页面开发中',
				icon: 'none'
			})
		},
		
		handleLogout() {
			uni.showModal({
				title: '退出登录',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除用户信息
						uni.removeStorageSync('userInfo')
						this.userInfo = {
							username: '游客用户',
							level: '普通用户',
							avatar: '/static/logo.png',
							isLogin: false
						}
						this.userStats = {
							favorites: 0,
							history: 0,
							reviews: 0
						}
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						})
					}
				}
			})
		},
		
		showLoginTip() {
			uni.showModal({
				title: '提示',
				content: '请先登录后再使用此功能',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						this.goToLogin()
					}
				}
			})
		}
	}
}
</script>

<style scoped>
.profile-container {
	background: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx; /* 为底部导航栏留出空间 */
}

.profile-header {
	background: #ffffff;
	padding: 40rpx;
	border-bottom: 1rpx solid #e0e0e0;
}

.user-info {
	display: flex;
	align-items: center;
	margin-bottom: 40rpx;
}

.avatar-container {
	position: relative;
	margin-right: 30rpx;
}

.avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.avatar-container .avatar {
	margin-right: 0;
}

.avatar-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	border-radius: 60rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	opacity: 0;
	transition: opacity 0.3s ease;
}

.avatar-container:active .avatar-overlay {
	opacity: 1;
}

.avatar-text {
	color: #ffffff;
	font-size: 20rpx;
	margin-top: 8rpx;
}

.user-details {
	flex: 1;
}

.username {
	color: #333333;
	font-size: 36rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 10rpx;
}

.user-level {
	color: #ff6b35;
	font-size: 24rpx;
	padding: 8rpx 16rpx;
	background: rgba(255, 107, 53, 0.1);
	border-radius: 20rpx;
	display: inline-block;
}

.login-btn {
	padding: 16rpx 32rpx;
	background: linear-gradient(45deg, #ff6b35, #ff8c42);
	border-radius: 30rpx;
}

.login-btn text {
	color: #ffffff;
	font-size: 28rpx;
}

.stats-section {
	display: flex;
	justify-content: space-around;
}

.stat-item {
	text-align: center;
}

.stat-number {
	color: #333333;
	font-size: 36rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 10rpx;
}

.stat-label {
	color: #999999;
	font-size: 24rpx;
}

.menu-sections {
	padding: 20rpx;
}

.menu-section {
	margin-bottom: 40rpx;
}

.section-title {
	color: #333333;
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
	padding-left: 20rpx;
}

.menu-list {
	background: #ffffff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
	display: flex;
	align-items: center;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-text {
	color: #333333;
	font-size: 28rpx;
	flex: 1;
	margin-left: 20rpx;
}

.cache-size {
	color: #999999;
	font-size: 24rpx;
	margin-right: 10rpx;
}

.logout {
	justify-content: center;
}

.logout-text {
	color: #ff4444;
	margin-left: 10rpx;
}

.admin-item {
	background: linear-gradient(135deg, rgba(255, 107, 53, 0.05), rgba(255, 140, 66, 0.05));
	border: 1rpx solid rgba(255, 107, 53, 0.2);
}

.admin-text {
	font-weight: bold;
	color: #ff6b35;
}

.admin-badge {
	background: #ff6b35;
	color: white;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	margin-right: 15rpx;
}

.badge-text {
	font-size: 20rpx;
	font-weight: bold;
}
</style>
